package cn.hss.map;

import org.junit.Test;

import java.util.*;

/**
 * @author 作者：HeShaoShuai
 * @Email 邮箱：2569819541@qq.com
 * @Date 日期：2023/4/28 8:11
 * @Package 包名：cn.hss.map
 * @Project 项目名：JavaSE
 * @Version 1.0
 */
public class TreeMapTest {
	@Test
	public void testHashTable(){
		Hashtable hashTable = new Hashtable<>();
		hashTable.put("number"+1, 1);
		hashTable.put("number"+2, 2);
		hashTable.put("number"+3, 3);
		hashTable.put("number"+4, 4);
		hashTable.put("number"+5, 5);
		hashTable.put("number"+1, 100);//替换value的值
		//HashTable中key/value不能为null
		//hashTable.put(null, 6);//NullPointerException异常
		//hashTable.put(1, null);//NullPointerException异常
		System.out.println(hashTable);

	}
	//定制排序
    /*需求：先按照name从大到小的顺序排列，即降序；
    如果name相等，则按照年龄从小到大的顺序排序，即升序
    * */
	@Test
	public void testTreeMap(){
		TreeMap map =
				new TreeMap(new Comparator() {
					@Override
					public int compare(Object o1,Object o2) {
						if(o1 instanceof Person && o2 instanceof Person){
							Person p1=(Person) o1;
							Person p2=(Person) o2;
							//先按照name从大到小的顺序排列，即降序.前面加负号表示降序排序
							int compare = -p1.getName()
									.compareTo(p2.getName());
							if(compare != 0){
								return compare;
							}else{
								//如果name相等，则按照年龄从小到大的顺序排序，即升序
								return Integer.compare(p1.getAge(), p2.getAge());
							}
						}else{
							throw new RuntimeException("类型不匹配");
						}
					}
				});
		//创建对象
		Person tom = new Person("Tom", 18);
		Person jack = new Person("Jack", 38);
		Person tom1 = new Person("Tom", 28);
		Person hanMei = new Person("HanMei", 20);
		//将对象添加到集合中
		map.put(tom, 111);
		map.put(jack, 222);
		map.put(tom1, 333);
		map.put(hanMei, 444);
		//遍历集合
		map.forEach((k,y)-> System.out.println(k+"--->"+y));
	}
	//TreeMap中的自然排序
	@Test
	public void testPerson(){
		//T-84 J-74
		Person tom = new Person("Tom", 18);
		Person jack = new Person("Jack", 18);
		Person rose = new Person("Rose", 28);
		Person hanMei = new Person("HanMei", 20);
		Person liLei = new Person("LiLei", 38);
		TreeMap treeMap = new TreeMap<>();
		treeMap.put(tom,11);
		treeMap.put(jack,22);
		treeMap.put(rose,33);
		treeMap.put(hanMei,44);
		treeMap.put(liLei,55);
		//遍历treeMap
		Iterator it = treeMap.entrySet().iterator();
		while(it.hasNext()){
			Object obj = it.next();
			Map.Entry entry=(Map.Entry)obj;
			System.out.println(entry.getKey()+"--->"+
					entry.getValue());
		}
	}
}